#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define endl '\n'
const int N = 2e5 + 5;

int n, m;
int ed[N];
int tr[N][26], v[N][26], fail[N], num;
vector<int> e[N];
void build_ac() {
  queue<int> q;
  rep(i, 0, 25) if (tr[0][i]) q.push(tr[0][i]);
  while (q.size()) {
    int p = q.front();
    q.pop();
    rep(i, 0, 25) {
      if (tr[p][i]) {
        q.push(tr[p][i]);
        int fp = fail[tr[p][i]] = tr[fail[p]][i];
      } else {
        v[p][i] = 1;
        tr[p][i] = tr[fail[p]][i];
      }
    }
  }
}
void build_fail_tree() { rep(i, 1, num) e[fail[i]].push_back(i); }
int dfn[N], sz[N], seq[N], tot;
void dfs(int u, int fu) {
  dfn[u] = ++tot;
  sz[u] = 1;
  for (int v : e[u]) {
    dfs(v, u);
    sz[u] += sz[v];
  }
}
int bit[N];
int lowbit(int x) { return x & -x; }
void update(int x, int d) {
  for (int i = x; i <= num + 1; i += lowbit(i)) bit[i] += d;
}
int query(int x) {
  int res = 0;
  for (int i = x; i > 0; i -= lowbit(i)) res += bit[i];
  return res;
}
vector<pii> qs[N];
int ans[N];
int query_p(int p) {
  int l = dfn[p], r = dfn[p] + sz[p] - 1;
  return query(r) - query(l - 1);
}
void dfs2(int p) {
  update(dfn[p], 1);
  for (pii x : qs[p]) {
    ans[x.first] = query_p(x.second);
  }
  rep(i, 0, 25) if (tr[p][i] && !v[p][i]) dfs2(tr[p][i]);
  update(dfn[p], -1);
}
int st[N], top;
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  string t;
  cin >> t;
  for (char c : t) {
    if (c == 'B') {
      if (top) top--;
    } else if (c == 'P') {
      ed[++n] = st[top];
    } else {
      int ch = c - 'a';
      int p = st[top];
      if (!tr[p][ch]) tr[p][ch] = ++num;
      st[++top] = tr[p][ch];
    }
  }
  build_ac();
  build_fail_tree();
  dfs(0, 0);
  cin >> m;
  rep(i, 1, m) {
    int u, v;
    cin >> u >> v;
    qs[ed[v]].push_back(pii(i, ed[u]));
  }
  dfs2(0);
  rep(i, 1, m) cout << ans[i] << endl;
  return 0;
}